package com.gogowan.agroenterprise.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.gogowan.agroenterprise.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ioid.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class ListDataSave<T> {

    public ListDataSave() {
    }

    /**
     * 保存List
     * @param tag
     * @param datalist
     */
    public <T> void setDataList(String tag, List<T> datalist) {
        if (null == datalist || datalist.size() <= 0){
            MyApplication.editor.putString(tag, "");
            MyApplication.editor.commit();
            return;
        }


        Gson gson = new Gson();
        //转换成json数据，再保存
        String strJson = gson.toJson(datalist);
        MyApplication.editor.putString(tag, strJson);
        MyApplication.editor.commit();

    }

    /**
     * 获取List
     * @param tag
     * @return
     */
    public <T> List<T> getDataList(String tag) {
        List<T> datalist=new ArrayList<T>();
        String strJson = MyApplication.mSettings.getString(tag, null);
        if (null == strJson|| StringUtils.isEmpty(strJson)||"[]".equals(strJson)) {
            return datalist;
        }
        Gson gson = new Gson();
        datalist = gson.fromJson(strJson, new TypeToken<List<T>>() {
        }.getType());
        return datalist;

    }
}
